package com.woniuxy.car.commodity.service.core.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.car.commodity.service.core.common.MyAssert;
import com.woniuxy.car.commodity.service.core.dto.CommodityDto;
import com.woniuxy.car.commodity.service.core.entity.Commodity;
import com.woniuxy.car.commodity.service.core.entity.CommodityFormat;
import com.woniuxy.car.commodity.service.core.entity.CommodityParam;
import com.woniuxy.car.commodity.service.core.entity.CommodityPics;
import com.woniuxy.car.commodity.service.core.mapper.CommodityMapper;
import com.woniuxy.car.commodity.service.core.service.ICommodityFormatService;
import com.woniuxy.car.commodity.service.core.service.ICommodityParamService;
import com.woniuxy.car.commodity.service.core.service.ICommodityPicsService;
import com.woniuxy.car.commodity.service.core.service.ICommodityService;
import com.woniuxy.common.exception.BusinessException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author awz
 * @since 2022-03-01
 */
@AllArgsConstructor
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, Commodity> implements ICommodityService {

    private CommodityMapper commodityMapper;

    private ICommodityPicsService commodityPicsService;

    private ICommodityParamService commodityParamService;

    private ICommodityFormatService commodityFormatService;

    @Override
    public void groundingOrDown(int id, int status) {


        //查询商品是否存在及商品上下架状态
        Commodity commodity = baseMapper.selectById(id);
        if(ObjectUtil.isNull(commodity) || commodity.getGrounding() == status){
            switch (status){
                case 0:
                    throw new BusinessException("商品不存在或商品已经下架");
                default:
                    throw new BusinessException("商品不存在或商品已经上架");
            }

        }
        //修改商品上下架状态
        commodity.setGrounding(status);
        switch (status){
            case 0:
                commodity.setDownTime(LocalDateTime.now());
                break;
            default:
                commodity.setGroundingTime(LocalDateTime.now());
                break;
        }
        baseMapper.updateById(commodity);
    }

    @Override
    public List<Commodity> findCommoditiesByIds(List<Integer> ids) {

        List<Commodity> commodities = baseMapper.selectBatchIds(ids);

        return commodities;
    }

    @Override
    public Commodity findCommodityById(int id) {
        Commodity commodity = baseMapper.selectById(id);
        return commodity;
    }

    @Override
    public void deleteCommodity(int id) {
        baseMapper.deleteById(id);
    }

    @Override
    public void addCommodity(CommodityDto commodityDto) {
        try {
            MyAssert.notEmpty(commodityDto.getTitle(),"商品标题不能为空");
            MyAssert.notEmpty(commodityDto.getName(), "商品名不能为空");
            MyAssert.notEmpty(commodityDto.getClassId(), "商品类别不能为空");
            MyAssert.notEmpty(commodityDto.getToShop(), "商品是否到店安装不能为空");
            MyAssert.notEmpty(commodityDto.getPic(), "商品图片不能为空");
            MyAssert.notEmpty(commodityDto.getPics(), "商品轮播图不能为空");
            MyAssert.notEmpty(commodityDto.getPrice(), "商品价格不能为空");
            MyAssert.notEmpty(commodityDto.getShopId(), "店铺id不能为空");
            MyAssert.notEmpty(commodityDto.getNextDayAir(), "是否是次日达不能为空");
            MyAssert.notEmpty(commodityDto.getCertified(), "是否是正品自营不能为空");
        } catch (BusinessException e) {
            throw new BusinessException(e.getMessage());
        }
        Commodity commodity = new Commodity();
        commodity.setTitle(commodityDto.getTitle());
        commodity.setName(commodityDto.getName());
        commodity.setClassId(commodityDto.getClassId());
        commodity.setToShop(commodityDto.getToShop());
        commodity.setPic(commodityDto.getPic());
        commodity.setVideo(commodityDto.getVideo());
        commodity.setPrice(commodityDto.getPrice());
        if(ObjectUtil.isNotEmpty(commodityDto.getStock())){
            commodity.setStock(commodityDto.getStock());
        }
        if(ObjectUtil.isNotEmpty(commodityDto.getPromotionPrice())){
            commodity.setPromotionPrice(commodityDto.getPromotionPrice());
        }
        commodity.setShopId(commodityDto.getShopId());
        if(ObjectUtil.isNotEmpty(commodityDto.getLabel())){
            commodity.setLabel(commodityDto.getLabel().toString());
        }
        if(ObjectUtil.isNotEmpty(commodityDto.getLimitCount())){
            commodity.setLimitCount(commodityDto.getLimitCount());
        }
        commodity.setNextDayAir(commodityDto.getNextDayAir());
        commodity.setCertified(commodityDto.getCertified());
        //添加商品
        baseMapper.insert(commodity);
        //添加商品轮播图
        List<String> pics = commodityDto.getPics();
        ArrayList<CommodityPics> commodityPics = new ArrayList<>();
        for (String pic : pics) {
            CommodityPics commodityPic = new CommodityPics();
            commodityPic.setCommodityId(commodity.getId());
            commodityPic.setUrl(pic);
            commodityPics.add(commodityPic);
        }
        commodityPicsService.saveBatch(commodityPics);
        //添加商品参数
        if(ObjectUtil.isNotEmpty(commodityDto.getParam())){
            CommodityParam commodityParam = new CommodityParam();
            commodityParam.setCommodityId(commodity.getId());
            commodityParam.setParamData(JSONUtil.parse(commodityDto.getParam()).toString());
            commodityParamService.save(commodityParam);
        }
        //添加商品规格
        if(ObjectUtil.isNotEmpty(commodityDto.getFormat())){
            CommodityFormat commodityFormat = new CommodityFormat();
            commodityFormat.setCommodityId(commodity.getId());
            commodityFormat.setFormatData(JSONUtil.parse(commodityDto.getFormat()).toString());
            commodityFormatService.save(commodityFormat);
        }
    }


    @Override
    public List<Commodity> showCommodities(CommodityDto commodityDto) {
        List<Commodity> commodities = new ArrayList<>();
        LambdaQueryWrapper<Commodity> wrapper = new LambdaQueryWrapper<>();
        //查询上架的商品
        wrapper.eq(Commodity::getGrounding, 1);
        if(ObjectUtil.isNotEmpty(commodityDto.getKeywords())){
            //如果有搜索内容
            wrapper.like(Commodity::getTitle, commodityDto.getKeywords());
        } else if(ObjectUtil.isNotEmpty(commodityDto.getClassId())) {
            //查询指定类别id的商品列表
            wrapper.eq(Commodity::getClassId, commodityDto.getClassId());
        } else {
            throw new BusinessException("请根据商品类别或关键字查询");
        }
        //默认排序规则为1
        int orderRule = 1;
        //判断排序规则
        if(ObjectUtil.isNotEmpty(commodityDto.getOrderRule())){
            orderRule = commodityDto.getOrderRule();
        }
        switch (orderRule){
            //综合
            case 1:
                //根据综合排序数降序排序
                wrapper.orderByDesc(Commodity::getSynthesize);
                //判断有无价格区间
                checkHasPriceRegion(commodityDto, wrapper);
                commodities = baseMapper.selectList(wrapper);
                break;
            //价格升序
            case 2:
                //根据价格升序排序
                wrapper.orderByAsc(Commodity::getPromotionPrice);
                //判断有无价格区间
                checkHasPriceRegion(commodityDto, wrapper);
                commodities = baseMapper.selectList(wrapper);
                break;
            //价格降序
            case 3:
                wrapper.orderByDesc(Commodity::getPromotionPrice);
                //判断有无价格区间
                checkHasPriceRegion(commodityDto, wrapper);
                commodities = baseMapper.selectList(wrapper);
                break;
            //销量降序
            case 4:
                wrapper.orderByDesc(Commodity::getSaleNum);
                //判断有无价格区间
                checkHasPriceRegion(commodityDto, wrapper);
                commodities = baseMapper.selectList(wrapper);
                break;
            //其他
            default:
                throw new BusinessException("排序规则错误");
        }
        //如果有标签筛选
        if(ObjectUtil.isNotEmpty(commodityDto.getLabel())){
            List<Commodity> commodityList = new ArrayList<>();
            //获取客户端选择的标签
            List<String> checkLabels = commodityDto.getLabel();
            for (Commodity commodity : commodities) {
                //获取查询的商品的标签
                JSONObject jsonObject = JSONUtil.parseObj(commodity.getLabel());
                List<String> labels = (List<String>) jsonObject.get("params");
                //筛选出包含客户选择的标签的商品
                if(labels.containsAll(checkLabels)){
                    commodityList.add(commodity);
                }
            }
            return commodityList;
        }

        return commodities;
    }

    private void checkHasPriceRegion(CommodityDto commodityDto, LambdaQueryWrapper<Commodity> wrapper) {
        if(!(ObjectUtil.isEmpty(commodityDto.getLowPrice()) && ObjectUtil.isEmpty(commodityDto.getHighPrice()))){
            //有价格区间
            wrapper.between(Commodity::getPromotionPrice, commodityDto.getLowPrice(), commodityDto.getHighPrice());
        }
    }
}
